package cn.walls1717.wallsmall.common.utils;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 数据库重复字段自动填充
 *
 * @author walls1717
 * @since 2022/10/30 11:05
 **/
@Slf4j
@Component
public class RepeatFieldsHandler implements MetaObjectHandler {
    /**
     * 插入操作自动填充
     *
     * @param metaObject metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert] -> {}", metaObject.toString());
        if (metaObject.hasSetter("createTime")) {
            metaObject.setValue("createTime", new Date());
        }
        if (metaObject.hasSetter("updateTime")) {
            metaObject.setValue("updateTime", new Date());
        }
    }

    /**
     * 更新操作自动填充
     *
     * @param metaObject metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update] -> {}", metaObject.toString());
        if (metaObject.hasSetter("updateTime")) {
            metaObject.setValue("updateTime", new Date());
        }
    }
}
